var express = require('express');
var router  = express.Router();
var http  = require('http');
var MongoClient = require('mongodb').MongoClient;
var DB_CONN_STR = 'mongodb://localhost:27017/user';
router.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By",' 3.2.1')
    res.header("Content-Type", "application/json;charset=utf-8");
    next();
})

router.get('/login',function(req,res) {
	var username = req.query.username;
	var userpwd = req.query.userpwd;
	MongoClient.connect(DB_CONN_STR,function(err,db) {
		if(err){
			console.log(err);
		}else{
			var coll = db.collection('userinfo');
			var data = {
				code:0,
				msg:'登录成功'
			}
			coll.find({username:username}).count(function(err,num) {
				if (num>0) {
					coll.find({username:username,userpwd:userpwd}).count(function(err,num) {
						if (num>0) {
							res.send(data)
						} else {
							data.code = 1;
							data.msg = '用户名或密码不正确';
							res.send(data);
						}
						db.close();
					})
					
				}else{
					coll.insertOne({username:username,userpwd:userpwd},function(err,result) {
						if (err) {
							data.code = -2;
							data.msg = '注册失败';
							res.send(data);
						} else {
							res.send(data);
						}
						db.close();
					})
				}
			})
		}
	})
})
module.exports = router;